package com.jinghua.treatment.wechat.util;

import com.alibaba.fastjson.JSONObject;
import com.jinghua.treatment.tools.PropertyUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.Date;
import java.util.List;

/**
 * 微信的一些全局变量存储和方法
 */

public class WechatUtil {

    static Logger logger = LogManager.getLogger(WechatUtil.class);

    final static long ACCESS_TOKEN_EXPIRED = 7000*1000;//微信token 过期时间 为7200秒，这里保留阈值时间
    /**
     * 访问票根，7200秒需要重新获取一次
     */
    public static String accessToken;
    private static Date storeTimeOfAccess;

    /**
     * 获取微信API的accessToken
     *
     * @return
     */
    public static String getAccessToken() {
        if(accessToken != null){//有值都话看看是否过期
            if(new Date().getTime() - storeTimeOfAccess.getTime()<ACCESS_TOKEN_EXPIRED){
                return  accessToken;
            }
        }
        String result = HttpUtil.sendGetRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + PropertyUtil.getConfig("wechat.appId") + "&secret=" + PropertyUtil.getConfig("wechat.secret"), null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getString("access_token") != null) {
            accessToken = (String) jsonObject.get("access_token");
            storeTimeOfAccess = new Date();
            logger.debug("get access_token success:" + accessToken);
        } else {
            //TODO 需要设计全局异常处理代码
           // throw new BizErrorException("获取微信access_token失败");
        }
        return   accessToken;
    }
    //
    public static void parseJsonToObject(String json ,Object targetObj){

    }

}
